package Tree;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * 中序遍历
 */
public class inorderTraversal {
    /**
     * 递归遍历
     */
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        inorder(root, list);
        return list;
    }

    public void inorder(TreeNode root, List<Integer> list) {
        if (root == null)
            return;
        inorder(root.left, list);
        list.add(root.val);
        inorder(root.right, list);
    }

    /**
     * 迭代遍历
     */
    public List<Integer> inorderTraversal2(TreeNode root) {
        if (root == null) {
            return new ArrayList<>();
        }
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            if (cur != null) {
                stack.push(cur);
                cur = cur.left; //左
            } else {
                cur = stack.pop();
                list.add(cur.val);  //中
                cur = cur.right;    //右
            }
        }
        return list;
    }

    /**
     * hot100一刷
     * hot100二刷
     */
    class Solution {
        public List<Integer> inorderTraversal(TreeNode root) {
            if (root == null)
                return new ArrayList<>();
            List<Integer> res = new ArrayList<>();
            Stack<TreeNode> stack = new Stack<>();
            TreeNode cur = root;
            stack.push(root);
            while (cur != null && !stack.isEmpty()) {
                if (cur.left != null) {
                    stack.push(cur.left);
                    cur = cur.left;
                } else {
                    TreeNode node = stack.pop();
                    res.add(node.val);
                    if (node.right != null) {
                        stack.push(node.right);
                        cur=node.right;
                    }
                }
            }
            return res;
        }
    }

    /**
     * 统一迭代遍历
     * 右中左-->左中右
     */
    public List<Integer> inorderTraversal3(TreeNode root) {
        if (root == null) {
            return new ArrayList<>();
        }
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode cur = stack.peek();
            if (cur != null) {
                TreeNode node = stack.pop();
                if (node.right != null) {
                    stack.push(node.right);//右
                }
                stack.push(node);   //中
                stack.push(null);
                if (node.left != null) {
                    stack.push(node.left);//左
                }
            }else {
                stack.pop();
                list.add(stack.pop().val);
            }
        }
        return list;
    }

}
